<!-- 新建实物奖品 -->
<template>
  <a-drawer v-model:visible="vdata.visible" :maskClosable="false" width="40%">
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span v-if="vdata.isAdd">新增虚拟卡券</span>
        <span v-if="!vdata.isAdd">修改虚拟卡券</span>
        <a-button :disabled="vdata.disabled" @click="onSaveDraft">保存草稿</a-button>
      </div>
    </template>
    <Step :current-step="vdata.currentStep" :steps="stepsConfig" />
    <a-form
      v-if="vdata.currentStep==0"
      ref="stepForm0Ref"
      :model="vdata.baseObject"
      layout="vertical"
      labelAlign="left"
      :rules="vdata.rules"
      :colon="false"
      :wrapper-col="{ span: 22 }"
      style="margin-top: 30px; margin-left: 20px"
    >
      <a-row>
        <a-col :span="12">
          <a-form-item label="机构" name="agentNo">
            <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.baseObject['agentNo']" :disabled="!vdata.isAdd" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="选择内部商品" name="virtualInsideId">
            <a-select
              ref="select"
              v-model:value="vdata.baseObject['virtualInsideId']"
              style="width: 100%"
              placeholder="请选择内部商品"
              @change="handleChange"
            > 
              <a-select-option v-for="(item, index) in ruleListProduct" :key="index" :lable="item.goodsName " :value="item.virtualInsideId">
                {{ item.goodsName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="数量" name="goodsNum">
            <a-input-number
              v-model:value="vdata.baseObject['goodsNum']"
              :min="vdata.minVirtualCouponNum"
              placeholder="数量"
              style="width: 100%;"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <Setting v-if="vdata.currentStep==1" ref="stepForm1Ref" :disabled="vdata.disabled" :awardSettingId="awardSettingId" @sendData="handleChildrenData" />
    <MerchantFrom v-if="vdata.currentStep == 2" ref="stepForm2Ref" :awardId="vdata.baseObject.couponId" :awardType="awardType" />
    <PersonnelFrom v-if="vdata.currentStep == 3" ref="stepForm3Ref" :awardId="vdata.baseObject.couponId" :awardType="awardType" :isEmployee="vdata.baseObject.isEmployee" />
    <InstitutionFrom
      v-if="vdata.currentStep == 4"
      ref="stepForm4Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isAllocation="vdata.baseObject.isAllocation"
      :agentNo="vdata.baseObject.agentNo"
      :isPush="vdata.disabled"
    />
    <div class="drawer-btn-center">
      <a-button v-if="vdata.currentStep != 0" style="margin-right:8px" @click="onSteps(-1)">
        <step-backward-outlined />
        上一步
      </a-button>
      <a-button v-if="vdata.currentStep != 4" :loading="vdata.btnLoading" style="margin-right:8px" @click="onSteps(1)">
        <step-forward-outlined />
        下一步
      </a-button>
      <a-button
        v-if="vdata.currentStep == 4"
        type="primary"
        :loading="vdata.btnLoading"
        @click="onSave(false)"
      >
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import{$virtualDetail,$virtualAdd,$virtualEdit,$getVirtualGoodsGoods,$virtualState}from '@/api/awardMange/virtualCoupon/index'
import{$addStting,$updateStting}from '@/api/awardMange/coupon/index'
import { reactive, ref, defineExpose, watch,onMounted, getCurrentInstance } from 'vue'
import Step from '../components/step/index.vue'
import Setting from '../components/setting/index.vue'
 import PersonnelFrom from '../components/PersonnelFrom/index.vue'
 import MerchantFrom from '../components/MerchantFrom/index.vue'
import InstitutionFrom from '../components/InstitutionFrom/index.vue'
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
const { proxy }: any = getCurrentInstance()
const stepsConfig = ref([
  { title: '虚拟券基本信息' },
  { title: '虚拟券配置信息' },
  { title: '可核销商户' },
  { title: '可派发人员' },
  { title: '虚拟券数量配置' }
])

const props = defineProps(['callbackFunc']) 
const awardType = ref(2)
const stepForm0Ref = ref()
const stepForm1Ref = ref()
const stepForm2Ref = ref()
const stepForm3Ref = ref()
const stepForm4Ref = ref()

const vdata: any = reactive({
  isAdd: false, // 新增OR修改
  visible: false,
  btnLoading: true,
  minVirtualCouponNum: 1,
  disabled: false,
  baseObject: {},
  rules: {
    agentNo: [{ required: true, message: '机构号不能为空', trigger: 'blur' },],
    goodsNum: [{ required: true, message: '数量不能为空', trigger: 'blur' },],
    insideGoodsId: [{ required: true, message: '内部商品不能为空', trigger: 'change' },],
    // isLimitUser: [{ required: true, message: '发放客户限制不能为空', trigger: 'change' },],
    everyoneMaxNum :[{ required: true, message: '数量不能为空', trigger: 'blur' },],
    limitUserContent: [{ required: true, message: '等级不能为空', trigger: 'change' },],
  },
})
const productObj = ref({}) as any 
const productType = ref('') as any 
function handleChange(val) {
productObj.value =  ruleListProduct.value.filter(item=>item.virtualInsideId == val)
productType.value = productObj.value.type
}
const ruleListProduct = ref([{
  virtualInsideId: null,
  goodsName: '',
}])


/**
 * 保存草稿
 */
function onSaveDraft(){
  if(vdata.currentStep == 0){ // 在第一步 保存草稿
    // 移除校验结果
    clearFieldValidate()
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validate(['virtualCouponName']).then(() => {  // 草稿只验证商品名称
      step0Request(true,true)
    }).catch(()=>{})
  }else if (vdata.currentStep === 1) {
      saveStting()
    // 第二步 保存草稿
    onClose()
  } else if(vdata.currentStep==2) {
    $infoBox.message.success('保存成功')
    onClose()
  }else if(vdata.currentStep==3){
     proxy.$refs['stepForm3Ref'].handleIsEmployeeChange()
      $infoBox.message.success('保存成功')
    onClose()
  }else{
     proxy.$refs['stepForm4Ref'].handleIsAllocationChange()
      $infoBox.message.success('保存成功')
      onClose()
  }
}


/**
 * 切换步骤
 */
function onSteps(step: number) {
  if (step < 0) {
    vdata.currentStep--
  } else {
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validate().then(() => {
      // 第一步网络请求 奖品信息
      if(vdata.currentStep === 0){
        step0Request(false)
      }else if(vdata.currentStep===1){
          saveStting()
        } else if (vdata.currentStep === 2 || vdata.currentStep === 3) {
          // 第二步 上传可核销商户清单
          if(vdata.currentStep === 3){
          // 调用员工组件暴漏的 handleIsEmployeeChange
          proxy.$refs['stepForm3Ref'].handleIsEmployeeChange()
        
          }
          vdata.currentStep++
        }
        

    }).catch((err)=>{console.log(err)})
  }
}
const couponIdOne = ref()
const couponIdUpdate = ref()
const  baseObjectSetting = ref()

// 接受子组件传递过来的基本信息限制配置的对象 
 function handleChildrenData(childrenObject:any){  
  baseObjectSetting.value = childrenObject.childrenbaseObject
  if(vdata.isAdd){
    vdata.baseObject.couponId = couponIdOne.value
  }else{
    vdata.baseObject.couponId = couponIdUpdate.value
  }
  
 }
// 发起请求  第一步
function step0Request(isDraft: boolean, showMsg: boolean = false) {
 const uploadObject = JSON.parse(JSON.stringify(vdata.baseObject))
 // 删除冗余数据
 delete uploadObject.awardMchList
  if(vdata.isAdd &&!vdata.baseObject.virtualId) { // 新增
    $virtualAdd(uploadObject).then((res) => {
       couponIdOne.value = res.virtualId
    // 新增的时候不会走setting里面的暴漏处来的handleChildrenData这个方法所以拿不到 couponId
      vdata.baseObject.couponId = res.virtualId
      vdata.baseObject.virtualId = res.virtualId
     if(isDraft){
      if(showMsg){
        $infoBox.message.success('保存成功')
        onClose()
      }
      return
    }
    vdata.currentStep++
  }).finally(() => {
  })
  }else{
    $virtualEdit(uploadObject).then((res) => {      
   if(isDraft){
      if(showMsg){
        $infoBox.message.success('保存成功')
        onClose()
      }
      return
    }
    vdata.currentStep++
  }).finally(() => {
  })
  }
 
}

// 第二步

// 通过awardSettingId来查配置的详情
// 第二部网络请求
const awardSettingId = ref()
function saveStting(){  
   const uploadObject =  proxy.$refs['stepForm1Ref'].changehadleSaveStting()
    uploadObject.awardId =  vdata.baseObject.couponId
     uploadObject.awardType = awardType.value
      
  if(awardSettingId.value||uploadObject.awardSettingId){
  uploadObject.awardSettingId =  awardSettingId.value?awardSettingId.value:uploadObject.awardSettingId
  $updateStting(uploadObject).then((res) => { 
       vdata.currentStep++
  })
  }else{
  $addStting(uploadObject).then((res) => {      
      awardSettingId.value = res
    vdata.currentStep++
  })
  }

}


async function show(virtualId:any, disabled:any, virtualCouponNum:any) {
   vdata.baseObject = {
    virtualId: null,
    goodsNum: null,
    virtualInsideId: null,
    isAllocation: false, // 是否分配
    isEmployee: false, // 是否员工
  }
  vdata.isAdd = !virtualId
  vdata.virtualId = virtualId
  vdata.btnLoading = false
  vdata.minVirtualCouponNum = virtualCouponNum
  awardSettingId.value = null
  vdata.disabled = disabled
  vdata.currentStep = 0
  clearFieldValidate()
  if (vdata.isAdd) { // 新增
    $getVirtualGoodsGoods().then(res => {
      ruleListProduct.value = res
      vdata.visible = true
    })
  } else{
    $getVirtualGoodsGoods().then(res => {
      ruleListProduct.value = res
    })
    $virtualDetail({virtualId}).then((res)=>{
        vdata.baseObject = res
         couponIdUpdate.value = res.virtualId
        //  修改的时候拿到settingid去查setting信息
        if(res.awardSetting){
           vdata.baseObject.isAllocation=res.awardSetting?.isAllocation
          vdata.baseObject.isEmployee = res.awardSetting?.isAllocationUser
         awardSettingId.value = res.awardSetting?.awardSettingId
        }
        vdata.visible = true
    })
  }
}
/**
 * 最后的保存
 */
function onSave(isDraft: boolean) {
   proxy.$refs['stepForm4Ref'].handleIsAllocationChange()
  const  virtualId  = vdata.baseObject.couponId
  const state = isDraft ? 0 : 2
  $virtualState( { virtualId, state }).then(() => {
    $infoBox.message.success('保存成功')
    onClose()
  })
}

/**
 * 清除表单字段验证
 */
function clearFieldValidate(){
  if (proxy.$refs['stepForm' + vdata.currentStep + 'Ref'] != undefined) {
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].clearValidate() // 清除验证
  }
}
/**
 * 关闭弹层
 */
function onClose() {
  props.callbackFunc()
  vdata.baseObject.agentNo = '' // 关闭弹层时清空选择机构 以再重新打开时触发机构树请求
  vdata.visible = false
}
defineExpose({
  show,
})

</script>

<style lang="less" scoped>
.rule {
  display: flex;
  align-items: center;
  gap: 20px;

  * {
    flex-shrink: 0;
  }

  &:nth-child(n + 2) {
    margin-top: 10px;
  }
}

.cp {
  cursor: pointer;
}

.fz18 {
  font-size: 18px;
}
</style>
